<template>
  <div class="Me-account">
    <form @submit.prevent="submitForm">
      <div class="tou">
        <div>当前头像：</div>
        <div><img src="../../public/Me-headimg.png" alt="" /></div>
      </div>
      <div class="nickname">昵称 <input type="text" v-model="username" /></div>
      <div class="password">
        密码 <input type="password" v-model="password" />
      </div>
      <div class="email">邮箱 <input type="email" v-model="email" /></div>
      <button type="submit">修改</button>
    </form>
  </div>
</template>

<script>
// 假设你已引入 axios
import axios from "axios";

export default {
  data() {
    // 优先查找 localStorage，没有再查 sessionStorage
    let userInfo =
      localStorage.getItem("userInfo") || sessionStorage.getItem("userInfo");
    userInfo = userInfo ? JSON.parse(userInfo) : {};
    return {
      username: userInfo.username || "",
      password: userInfo.password || "",
      email: userInfo.email || "",
    };
  },
  methods: {
    submitForm() {
      axios
        .post("http://localhost:3000/updateUser", {
          username: this.username,
          newInfo: {
            email: this.email,
            password: this.password,
          },
        })
        .then((res) => {
          if (res.data.status === 200) {
            alert("用户信息修改成功");
            // 更新本地存储
            let userInfo =
              localStorage.getItem("userInfo") ||
              sessionStorage.getItem("userInfo");
            userInfo = userInfo ? JSON.parse(userInfo) : {};
            userInfo.email = this.email;
            userInfo.password = this.password;
            localStorage.setItem("userInfo", JSON.stringify(userInfo));
          } else {
            alert(res.data.message);
          }
        });
    },
  },
};
</script>

<style  scoped>
.Me-account {
  display: flex;
  flex-direction: column;
  width: 100%;
  align-items: center;
}
.Me-account .tou {
  display: flex;
  width: 100%;
  height: 80px;
  align-items: center;
  margin-bottom: 30px;
  margin-right: 30px;
}
.Me-account .tou img {
  margin-left: 30px;
  width: 80px;
  height: 80px;
  border-radius: 50%;
}

.nickname,
.password,
.email,
.gender {
  margin-bottom: 30px;
}
input {
  margin-left: 30px;
}
button {
  margin-top: 30px;
  margin-left: 100px;
  width: 80px;
  height: 30px;
  background-color: #ffa500;
  border: none;
  border-radius: 5px;
}
</style>